<template>
	<div class="productServiceList">
		<el-card shadow="hover">
			<div class="product-service-list mb15">
				<el-form ref="formDataRef" :inline="true" :model="formData" label-width="100px" class="demo-form-inline">
					<el-row>
						<el-col :span="8">
							<el-form-item label="关键词" prop="productName" style="width: 100%">
								<el-input maxlength="200" v-model="formData.productName" placeholder="关键词" clearable @keyup.enter="searchFun()"></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="关联商品SKU" prop="sku" style="width: 100%">
								<el-input show-word-limit maxlength="200" v-model="formData.sku" placeholder @keyup.enter="searchFun()" />
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="是否上架" prop="state" style="width: 100%">
								<el-select @change="searchFun()" v-model="formData.state" placeholder="">
									<el-option v-for="item in SHELF_STATUS" :key="item.value" :label="item.label" :value="item.value"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="上架时间" prop="time" style="width: 100%">
								<el-date-picker
									style="width: 100%"
									value-format="YYYY-MM-DD"
									v-model="formData.time"
									type="date"
									placeholder="选择日期"
								></el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="关联站点" prop="site" style="width: 100%">
								<el-select @change="searchFun()" v-model="formData.site" style="width: 100%" placeholder="">
									<el-option v-for="item in siteOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item>
								<div>
									<el-button type="primary" @click="init">搜索</el-button>
									<el-button @click="resetForm">重置</el-button>
								</div>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row>
						<el-col :span="2">
							<UploadBtn btnName="导入商品" :uploadUrl="`/product/after-sale-prod/admin/excel/in`" style="margin-right: 10px"> </UploadBtn>
						</el-col>
						<el-col :span="10" class="center">
							<el-button color="#626aef" :loading="exportLoading" @click="exportProdTemp">导出商品</el-button>

							<el-button color="#7762ef" :loading="publicLoading" @click="changePublicState(NO_SALE)">下架</el-button>
							<el-button color="#7762ef" :loading="publicLoading" @click="changePublicState(IN_SALE)">上架</el-button>
						</el-col>
						<el-col :span="12" style="text-align: right">
							<el-button type="success" @click="setDetailId(0)">新建商品</el-button>
						</el-col>
					</el-row>
				</el-form>
			</div>
			<el-table v-loading="loading" :data="tableData" style="width: 100%">
				<el-table-column prop="checked" label width="80px">
					<template #default="scope">
						<el-checkbox v-model="scope.row.checked" label></el-checkbox>
					</template>
				</el-table-column>
				<el-table-column prop="orderNumber" label="序号" show-overflow-tooltip></el-table-column>
				<el-table-column prop="productId" label="商品ID" show-overflow-tooltip></el-table-column>
				<el-table-column prop="productName" label="商品名称" show-overflow-tooltip></el-table-column>
				<el-table-column prop="sku" label="自编sku" show-overflow-tooltip></el-table-column>
				<el-table-column prop="site" label="关联站点" show-overflow-tooltip></el-table-column>
				<el-table-column prop="salesVolume" label="销量" sortable show-overflow-tooltip></el-table-column>
				<el-table-column label="状态" show-overflow-tooltip>
					<template #default="scope">
						<span>{{ getPublishStatusText(scope.row.state) }}</span>
					</template>
				</el-table-column>
				<el-table-column label="编辑" width="160px">
					<template #default="scope">
						<el-button text type="success" @click="changePublicState(scope.row.state === IN_SALE ? NO_SALE : IN_SALE, scope.row)">{{
							getPublishStatusText(scope.row.state === IN_SALE ? NO_SALE : IN_SALE)
						}}</el-button>
						<el-button text type="primary" @click="setDetailId(scope.row.id)">编辑</el-button>
						<el-button text type="danger" @click="beforeDelete(scope.row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
		</el-card>
		<el-dialog v-model="dialogVisible" :title="dialogTitle" destroy-on-close width="80%">
			<serviceDetail ref="serviceDetailRef" v-model:couponId="checkAfterSaleGoodsItemId" @reloadList="searchFun()" />
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onClose">取消</el-button>
					<el-button type="primary" @click="onSubmit">保存</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>
<script setup name="ProductService">
import { ElMessage, ElMessageBox } from 'element-plus';
import serviceDetail from './serviceDetail.vue';
import UploadBtn from '/@/components/common/upload/UploadBtn.vue';
import { siteOptions } from '/@/stores/cityList';
import { siteFormat } from '/@/utils/filters';
import useServiceState from '/@/utils/pageState/serviveState';
import { getCommonSiteList } from '/@/utils/commonRequest';
import { useServiceApi } from '/@/api/service';

const { getPublishStatusText, IN_SALE, NO_SALE, SHELF_STATUS } = useServiceState();
const { delAfterSaleGoods, getAfterSaleGoodsCount, getAfterSaleGoodsList, publishAfterSaleGoods, afterSaleGoodsExport } = useServiceApi();

const serviceDetailRef = ref();
const dialogVisible = ref(false);
const dialogTitle = ref('添加商品');
const formDataRef = ref();
let loading = ref(false);
let tableData = ref([]);
let checkAfterSaleGoodsItemId = ref(-1);
let formData = ref({
	productName: '',
	sku: '',
	state: '',
	time: null,
	site: 'all',
});
let footData = ref({
	totalNumberOfGoods: 0,
	totalNumberOfSku: 0,
	totalSales: 0,
});
const page = ref({
	pageSize: 10,
	current: 1,
	total: 0,
});
const $route = useRoute();
let publicLoading = ref(false);
let exportLoading = ref(false);

init();

function init() {
	if ($route.query.id) {
		checkAfterSaleGoodsItemId.value = Number($route.query.id);
	}
	getList();
	getCommonSiteList();
}

function resetForm() {
	formDataRef.value.resetFields();
}

function searchFun() {
	console.log(1111);
	if (loading.value) {
		return;
	}
	page.value = {
		pageSize: page.value.pageSize,
		current: 1,
		total: page.value.total,
	};
	getList();
}

async function getList() {
	if (loading.value) {
		return;
	}
	loading.value = true;

	try {
		let params = {
			current: page.value.current,
			pageSize: page.value.pageSize,
			publishTime: formData.value.time,
			relationSite: formData.value.site,
			keyword: formData.value.productName,
			relationSku: formData.value.sku,
			publishStatus: formData.value.state,
		};

		let res = await getAfterSaleGoodsList(params);
		let countRes = await getAfterSaleGoodsCount();
		if (res.code !== 200 || countRes.code !== 200) {
			loading.value = false;
			// ElMessage({
			//     type: "error",
			//     message: res.data.msg,
			// });
			return;
		}
		loading.value = false;
		page.value = {
			pageSize: res.data.pageSize,
			current: res.data.current,
			total: res.data.total,
		};

		let tempList = [];
		if (res.data.length !== 0) {
			tempList = res.data.data.map((item, index) => {
				return {
					id: item.afterSaleProdId,
					checked: false,
					orderNumber: (res.data.current - 1) * 10 + index + 1,
					productId: item.id,
					productName: item.productName,
					sku: item.sku,
					site: siteFormat(item.site),
					salesVolume: item.sales,
					state: item.publishStatus,
				};
			});
		}

		tableData.value = tempList;

		footData.value = {
			totalNumberOfGoods: countRes.data.productNum,
			totalNumberOfSku: countRes.data.skuNum,
			totalSales: countRes.data.sales,
		};
	} catch (error) {
		loading.value = false;
		console.error(error);
		ElMessage({
			type: 'error',
			message: '获取售后商品列表失败',
		});
	}
}

// 修改上下架状态
async function changePublicState(status, item) {
	if (loading.value || publicLoading.value) {
		return;
	}
	let idList = [];

	for (let index = 0; index < tableData.value.length; index++) {
		const element = tableData.value[index];
		if (element.checked) {
			idList.push(element.productId);
		}
	}

	if (item) {
		idList = [item.productId];
	}

	if (idList.length === 0) {
		return;
	}

	loading.value = true;
	publicLoading.value = true;

	try {
		let res = await publishAfterSaleGoods({
			idList,
			status,
		});
		if (res.code !== 200) {
			loading.value = false;
			publicLoading.value = false;
			// ElMessage({
			//     type: "error",
			//     message: res.data.msg,
			// });
			return;
		}
		loading.value = false;
		publicLoading.value = false;
		ElMessage({
			type: 'success',
			message: '上/下架成功',
		});
		getList();
	} catch (error) {
		loading.value = false;
		publicLoading.value = false;
		ElMessage({
			type: 'error',
			message: '上/下架失败',
		});
	}
}

// 结束的询问
function beforeDelete(item) {
	// 提示是否结束
	ElMessageBox.confirm(`确认删除${item.productName}？`, '删除售后商品', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(() => {
			// ElMessage({
			//     type: "success",
			//     message: "Delete completed",
			// });
			delFun(item.productId);
		})
		.catch(() => {
			// ElMessage({
			//     type: "info",
			//     message: "Delete canceled",
			// });
		});
}

// 结束
async function delFun(id) {
	if (loading.value) {
		return;
	}
	loading.value = true;

	try {
		let res = await delAfterSaleGoods({
			idList: [id],
		});
		if (res.code !== 200) {
			loading.value = false;
			// ElMessage({
			//     type: "error",
			//     message: res.data.msg,
			// });
			return;
		}
		loading.value = false;
		ElMessage({
			type: 'success',
			message: '删除成功',
		});
		getList();
	} catch (error) {
		loading.value = false;
		ElMessage({
			type: 'error',
			message: '删除失败',
		});
	}
}

// 设置详情的id
function setDetailId(id) {
	if (id === 0) {
		dialogTitle.value = '添加商品';
	} else {
		dialogTitle.value = '编辑商品';
	}
	dialogVisible.value = true;
	checkAfterSaleGoodsItemId.value = id;
}

// 导出
// 结束
async function exportProdTemp() {
	if (exportLoading.value) {
		return;
	}

	let idList = [];

	for (let index = 0; index < tableData.value.length; index++) {
		const element = tableData.value[index];
		if (element.checked) {
			idList.push(element.productId);
		}
	}

	exportLoading.value = true;

	console.log('0===', idList);

	try {
		getProdTempPromise(idList).then((response) => {
			const link = document.createElement('a');
			const url = window.URL.createObjectURL(new Blob([response], { type: 'application/vnd.ms-excel' }));
			link.setAttribute('href', url);
			link.setAttribute('download', '售后商品.xls');
			document.body.appendChild(link);
			link.click();
		});
		exportLoading.value = false;
	} catch (error) {
		exportLoading.value = false;
	}
}

async function getProdTempPromise(idList) {
	return await afterSaleGoodsExport({ idList });
}

const onClose = () => {
	serviceDetailRef.value.cancel();
	dialogVisible.value = false;
};
const onSubmit = () => {
	serviceDetailRef.value.submitForm();
	setTimeout(() => {
		dialogVisible.value = false;
	}, 500);
};
</script>
<style lang="scss" scoped></style>
